package com.itguigu.principle.segregation.improve;

/**
 * 按照接口隔离原则优化代码
 */
public class Segregation1 {
    public static void main(String[] args) {
        // a通过Interface1,和Interface3去调用D类的1,2,3方法
        A a = new A();
        a.depend1(new D());
        a.depend2(new D());
        a.depend3(new D());

        // c通过Interface1,和Interface2去调用B类的1,4,5方法
        C c =new C();
        c.depend1(new B());
        c.depend4(new B());
        c.depend5(new B());

    }
}

/**
 * 这里我们将原来的Interface1中的5个方法分别提取出最小接口
 */
interface Interface1 {
    void operation1();
}

interface Interface2 {
    void operation2();

    void operation3();
}

interface Interface3 {
    void operation4();

    void operation5();
}

/**
 * 采用多实现方式,实现接口隔离原则
 */
class B implements Interface1,Interface3{

    @Override
    public void operation1() {
        System.out.println("B实现了 operation1");
    }

    @Override
    public void operation4() {
        System.out.println("B实现了 operation4");
    }

    @Override
    public void operation5() {
        System.out.println("B实现了 operation5");
    }
}

/**
 * 采用了接口隔离方式,只需要重写需要的方法
 */
class D implements Interface1,Interface2{

    @Override
    public void operation1() {
        System.out.println("D实现了 operation1");
    }

    @Override
    public void operation2() {
        System.out.println("D实现了 operation2");
    }

    @Override
    public void operation3() {
        System.out.println("D实现了 operation2");
    }
}
/**
 * A类通过接口Interface1去使用D类
 * 但是只会用到D类方法1,2,3
 */
class A {
    public void depend1(Interface1 i) {
        i.operation1();
    }

    public void depend2(Interface2 i) {
        i.operation2();
    }

    public void depend3(Interface2 i) {
        i.operation3();
    }
}

/**
 * C类通过接口Interface1去使用B类
 * 但是只会用到B类方法1,4,5
 */
class C {
    public void depend1(Interface1 i) {
        i.operation1();
    }

    public void depend4(Interface3 i) {
        i.operation4();
    }

    public void depend5(Interface3 i) {
        i.operation5();
    }
}
